//
//  AIPViewController.m
//  FMS
//
//  Created by Steven on 10/15/13.
//  Copyright (c) 2013 QGSVN. All rights reserved.
//

#import "AIPViewController.h"
#import "ScheduleInspectionViewController.h"
#import "DetailedItemViewController.h"
#import "ScheduleBaseLite.h"
#import "UIScrollView+ScrollView.h"

#define WIDTH_COLUMN_ONE  220
#define WIDTH_COLUMN_TWO  200
#define WIDTH_COLUMN_THREE  220
#define WIDTH_COLUMN_FOUR  220

@interface AIPViewController ()

@end

@implementation AIPViewController
@synthesize delegate;
@synthesize itemDetailedDict;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil itemType:(int)_itemType
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        dictLanguage = [ApplicationDelegate.arrayLanguage objectAtIndex:0];
        itemType = _itemType;
    }
    return self;
}
- (void)listScheduleByType{
    
    isLoadMore = NO;
    int typeCategory;
    if (itemType == Building_Type)
    {
        typeCategory = Inspection;
    }
    else
        typeCategory = Maintenance;
    
    NSMutableDictionary *filterDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[self.itemDetailedDict objectForKey:@"service"],@"service",[self.itemDetailedDict objectForKey:@"camp"],@"camp",[self.itemDetailedDict objectForKey:@"unit"],@"unit",[self.itemDetailedDict objectForKey:@"building"],@"building",[self.itemDetailedDict objectForKey:@"floor"],@"floor", nil];
    if (itemType == Facility_Type)
    {
        [filterDict setObject:[self.itemDetailedDict objectForKey:@"room"] forKey:@"room"];
        [filterDict setObject:[NSNumber numberWithInt:Schedule_AMP_Mgmt_Type] forKey:SCHEDULE_MGMT_TYPE];
    }
    else
    {
        [filterDict setObject:[self.itemDetailedDict objectForKey:@"item_name"] forKey:@"room"];
        [filterDict setObject:[NSNumber numberWithInt:Schedule_AIP_Mgmt_Type] forKey:SCHEDULE_MGMT_TYPE];
    }
    [filterDict setObject:[self.itemDetailedDict objectForKey:@"_id"] forKey:@"itemId"];
//    [filterDict setObject:[NSNumber numberWithInt:typeCategory] forKey:@"categoryId"];
    NSMutableArray *array = [ScheduleBaseLite queryScheduleByItemId:filterDict from:indexSchedule numberPage:NUMBER_ROW_PAGE];
    
    [mainArray addObjectsFromArray:array];
    indexSchedule += [array count];
    [self.mainTableView reloadData];
    if ([array count] == NUMBER_ROW_PAGE) {
        isLoadMore = YES;
    }
    if (isLoadMore) {
        
        [self.mainTableView showLoadingMore];
    }
    else
        [self.mainTableView hideLoadingMore];
    [self.mainTableView hideActivity];
    [myActivityView stopAnimating];
}
- (void)reloadListSchedule{
    indexSchedule = 0;
    [mainArray removeAllObjects];
    [self listScheduleByType];
}

- (NSMutableDictionary *)getFirstItem{
    if ([mainArray count] == 0)
        return nil;
    else
        return [mainArray objectAtIndex:0];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _lbType.text        = [dictLanguage objectForKey:@"building-mgmt.aip.label-type"];
    _lbStartDate.text   = [dictLanguage objectForKey:@"maintenance-mgmt.inspection.starting-date"];
    
    self.lblTitleLastDone.text = [dictLanguage objectForKey:@"schedule.title-last-done"];
    self.lblTitleFrequency.text = [dictLanguage objectForKey:@"schedule.title-frequency"];
    
    mainArray = [NSMutableArray arrayWithCapacity:1];
    _mainTableView.separatorColor = APPLE_BLUE_COLOR;
    
    myActivityView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2, self.view.frame.size.height/2, 25, 25)];
    myActivityView.hidesWhenStopped = YES;
    myActivityView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    [self.view addSubview:myActivityView];
    [myActivityView startAnimating];
    
    [self performSelectorInBackground:@selector(reloadListSchedule) withObject:Nil];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [mainArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    // Configure the cell...
    NSMutableDictionary *dict = [mainArray objectAtIndex:indexPath.row];
    
    UILabel *lbCellItemType = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, WIDTH_COLUMN_ONE, 21)];
    lbCellItemType.backgroundColor = [UIColor clearColor];
    lbCellItemType.textColor = [UIColor darkGrayColor];
    lbCellItemType.text = [dict objectForKey:@"scheduleCategory"];
    [cell.contentView addSubview:lbCellItemType];
    
    UILabel *lblFrequency = [[UILabel alloc] initWithFrame:CGRectMake(250, 20, WIDTH_COLUMN_TWO, 21)];
    lblFrequency.backgroundColor = [UIColor clearColor];
    lblFrequency.textColor = [UIColor darkGrayColor];
    
    [cell.contentView addSubview:lblFrequency];
    
    UILabel *lblLastDate = [[UILabel alloc] initWithFrame:CGRectMake(470, 20, WIDTH_COLUMN_THREE, 21)];
    lblLastDate.backgroundColor = [UIColor clearColor];
    lblLastDate.textColor = [UIColor darkGrayColor];
    [cell.contentView addSubview:lblLastDate];
    
    UILabel *lbCellStartDate = [[UILabel alloc] initWithFrame:CGRectMake(690, 20, WIDTH_COLUMN_FOUR, 21)];
    lbCellStartDate.backgroundColor = [UIColor clearColor];
    lbCellStartDate.textColor = [UIColor darkGrayColor];
    [cell.contentView addSubview:lbCellStartDate];
    
    lbCellItemType.text = [dict objectForKey:@"scheduleCategory"];
    if ([[dict objectForKey:@"categoryId"] intValue] == Maintenance){
        lbCellItemType.text = [ApplicationDelegate getMaintenanceTypeName:[[dict objectForKey:@"maintenanceTypeId"] intValue]];
    }
    
    lbCellStartDate.text = [NSDate stringFormatTimeDateFromDate:[NSDate dateFormatDateFullFromString:[dict objectForKey:@"startDate"]]];
    
    if ([dict objectForKey:@"lastUpdate"] && ![[dict objectForKey:@"lastUpdate"] isEqualToString:@""]) {
        lblLastDate.text = [NSDate stringFormatTimeDateFromDate:[NSDate dateFormatDateFullFromString:[dict objectForKey:@"lastUpdate"]]];
    }
    switch ([[dict objectForKey:@"categoryTypeId"] intValue]) {
        case 0:

            break;
        case MONTHLY:
            lblFrequency.text = [dictLanguage objectForKey:@"schedule.title-monthly"];
            break;
        case QUATERLY:
            lblFrequency.text = [dictLanguage objectForKey:@"schedule.title-quaterly"];
            break;
        case YEARLY:
            lblFrequency.text = [dictLanguage objectForKey:@"schedule.title-yearly"];
            break;
        case TWO_YEARLY:
            lblFrequency.text = [dictLanguage objectForKey:@"schedule.title-two-yearly"];
            break;
        case FIVE_YEARLY:
            lblFrequency.text = [dictLanguage objectForKey:@"schedule.title-five-yearly"];
            break;
        case OTHER:
            lblFrequency.text = [dictLanguage objectForKey:@"schedule.title-other"];
            break;
        default:
            break;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSMutableDictionary *dictSchedule = [mainArray objectAtIndex:indexPath.row];
    ScheduleInspectionViewController *controller = [[ScheduleInspectionViewController alloc] initWithNibName:@"ScheduleInspectionViewController" bundle:[NSBundle mainBundle] schedule:dictSchedule];
    controller.delegate = delegate;
    controller.isEditting = YES;
    
    
    [((DetailedItemViewController *)delegate).navigationController pushViewController:controller animated:YES];
    [controller reloadInfoSchedule];
    
}


#pragma mark scrollview load more
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    didReadyLoadMore = NO;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    float bottomEdge = scrollView.contentOffset.y + scrollView.frame.size.height;
    if (bottomEdge >= scrollView.contentSize.height && !didReadyLoadMore)
    {
        didReadyLoadMore = YES;
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (didReadyLoadMore) {
        if(!isLoadMore)
        {
            [self.mainTableView hideLoadingMore];
            return;
        }
        [self.mainTableView showActivity];
        [self listScheduleByType];
    }
}
@end
